<template>
  <div class="m-box">
    <Tab :tabTitle="tabList" @activeId="tabActive" class="m-tab" />
    <div class="m-system">
      <div class="m-system-left">
        <p class="f-title">
          <span>菜单列表</span>
          <i v-if="selectMenuData.menuCode" class="el-icon-plus" @click="addMenu"></i>
        </p>
        <el-tree ref="tree" :data="menuData" node-key="menuCode" :default-expanded-keys="expandedArr" :default-checked-keys="checkedArr" :props="defaultProps" draggable :allow-drop="allowDrop" @node-drop="sort" @node-click="menuClick">
          <template #default="{ node, data }">
            <div :class="data.menuCode == selectMenuData.menuCode ? 'm-tree-node m-tree-active' : 'm-tree-node'">
              <div>
                <span class="icon"><i :class="data.menuType == 1 ? 'el-icon-folder' : 'el-icon-s-unfold'"></i></span>
                <span class="name">{{ node.label }}</span>
              </div>
              <div class="btn">
                <i v-if="data.menuType == 1" class="el-icon-plus" @click.stop="addChildMenu(node, data)"></i>
                <i class="el-icon-sort"></i>
              </div>
            </div>
          </template>
        </el-tree>
      </div>
      <div class="m-system-right">
        <div class="m-system-right-top">
          <div class="f-left">
            <p class="f-title">
              <span>{{selectMenuData.menuType==1 ? '目录信息' : '菜单信息'}}</span>
              <i class="el-icon-delete" @click="delMenu"></i>
            </p>
            <div v-if="menuInfo.menuName" class="f-content">
              <div class="f-img">
                <img src="@/assets/imgs/menu_icon.png">
              </div>
              <div class="f-text">
                <p>
                  <span>名称：{{menuInfo.menuName}}</span><span>类型：{{menuInfo.menuTypeName}}</span>
                  <span>key：oot</span><span>父级：{{menuInfo.parentMenuName}}</span>
                </p>
                <p>
                  描述：{{menuInfo.menuRemark}}
                </p>
              </div>
            </div>
            <div v-else class="f-content">
              <p class="f-notips">暂无数据</p>
            </div>
          </div>
          <div v-if="selectMenuData.menuType == 2" class="f-right">
            <p class="f-title">
              <span>数据权限</span>
              <i v-if="selectMenuData.menuCode" class="el-icon-plus"></i>
            </p>
            <div v-if="dataAuthList.length > 0" class="f-content">
              <el-checkbox v-model="checked">品牌数据</el-checkbox>
              <el-checkbox v-model="checked">门店数据</el-checkbox>
            </div>
            <div v-else class="f-content">
              <p class="f-notips">暂无数据</p>
            </div>
          </div>
        </div>
        <div v-if="selectMenuData.menuType == 2" class="m-system-right-bottom">
          <div class="f-left">
            <p class="f-title">
              <span>功能权限</span>
              <i v-if="selectMenuData.menuCode" class="el-icon-plus" @click="addAuthority"></i>
            </p>
            <ul class="f-list">
              <li class="f-list-tit">
                <p>功能</p>
                <p>KEY</p>
                <p>状态</p>
                <p>操作</p>
              </li>
              <template v-if="authority.length > 0">
              <li v-for="(item, index) in authority" :key="index">
                <p>{{item.buttonName}}</p>
                <p>{{item.key}}</p>
                <p>
                  <el-switch v-model="item.status" active-color="#31c0fd" inactive-color="#b4b4b4" :active-value='0' :inactive-value='1' @change="switchEvent(item.buttonCode, item.status)"></el-switch>
                </p>
                <p>
                  <i class="el-icon-delete" @click="delAuthority(item.buttonCode)"></i>
                </p>
              </li>
              </template>
              <template v-else>
                <li class="f-notips">暂无数据</li>
              </template>
            </ul>
          </div>
          <div class="f-right">
            <p class="f-title">
              <span>列权限</span>
              <i class="el-icon-plus" @click="addColumn"></i>
            </p>
            <template v-if="columnPower.length > 0">
            <div v-for="(item, index) in columnPower" :key="index" class="f-list">
              <div class="f-tops">
                <p>{{item.dataListName}} <i class="el-icon-caret-top"></i></p>
                <p class="f-tops-right">
                  <span class="search" @click="setQuickSearch"></span>
                  <span class="sensearch" @click="setSeniorSearch"></span>
                  <span class="delete" @click="delColumn(item.dataListCode)"></span>
                </p>
              </div>
              <ul class="f-childlist">
                <li v-for="items in item.attr" :key="items.dataListAttrCode">
                  <p class="name" @click="changeAlias()">{{items.dataListName}}</p>
                  <!-- <p v-else class="name">
                    <el-input v-model="items.dataListName" size="mini"></el-input>
                  </p> -->
                  <p class="sort">:</p>
                  <p class="switch">
                    <el-switch v-model="items.listVisible" active-color="#31c0fd" inactive-color="#b4b4b4" :active-value='0' :inactive-value='1' @change="listVisibleChange(items.dataListAttrCode, items.listVisible, 1)"></el-switch>
                  </p>
                  <p class="checkbox">
                    <el-checkbox class="f-checkbox" v-model="items.listHide" :true-label="1" :false-label="0" :disabled="items.listVisible ? true : false" @change="listVisibleChange(items.dataListAttrCode, items.listHide, 2)">列隐藏</el-checkbox>
                  </p>
                  <p class="checkbox">
                    <el-checkbox class="f-checkbox" v-model="items.listSort" :true-label="1" :false-label="0" :disabled="items.listVisible ? true : false" @change="listVisibleChange(items.dataListAttrCode, items.listSort, 3)">列排序</el-checkbox>
                  </p>
                  <p class="checkbox">
                    <el-checkbox class="f-checkbox" v-model="items.listAuth" :true-label="1" :false-label="0" :disabled="items.listVisible ? true : false" @change="listVisibleChange(items.dataListAttrCode, items.listAuth, 4)">列权限</el-checkbox>
                  </p>
                </li>
              </ul>
            </div>
            </template>
            <template v-else>
              <div class="f-notips">暂无数据</div>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
  <MenuPopups :isPopups="isPopups" :typeId="typeId" :menuItems="menuItems" :menuCode="selectMenuData.menuCode" :menuIdArr="menuIdArr" :parentData="selectMenuData" @closePop="closeMenuPop" />
</template>

<script>
import { reactive, watch, computed, ref, toRefs, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import Tab from '@/components/Tab'
import MenuPopups from './component/menuPopups'
import { menuTree, menuGet, menuDelete, menuSort, buttonPage, dataListPage, buttonUpdateState, updateDataListAttr, buttonDelete, dataListDelete } from '@/api/menu'
import { useStore } from 'vuex'

export default {
  components: {
    Tab,
    MenuPopups
  },
  setup() {
    const store = useStore()
    const state = reactive({
      tabList: [
        {
          menuItems: '1',
          name: '管理平台'
        },
        {
          menuItems: '2',
          name: '品牌'
        },
        {
          menuItems: '3',
          name: '商户'
        }
      ],
      menuItems: '1',
      menuData: [],
      menuInfo: {},
      dataAuthList: [],
      authority: [],
      columnPower: [],
      isPopups: false,
      typeId: 1,
      checked: false,
      value: '',
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      menuIdArr: [],
      selectMenuData: {}
    });
    watch(() => state.menuItems,(newProps, oldProps) => {
      if (newProps == oldProps) return
      state.menuInfo = {}
      state.authority = []
      state.columnPower = []
      getDataList()
    })
    if ( JSON.parse(localStorage.getItem("selectMenuData")) && Object.keys(JSON.parse(localStorage.getItem("selectMenuData"))).length !== 0) {
      let selectMenuData = JSON.parse(localStorage.getItem("selectMenuData"))
      let menuIdArr = localStorage.getItem("menuIdArr")
      state.selectMenuData = selectMenuData
      state.menuIdArr = menuIdArr.split(',')
      menuGet({code: state.selectMenuData.menuCode}).then((res) => {
        if (res.code === 200) {
          state.menuInfo = res.data
        } 
      })
      buttonPage({code: state.selectMenuData.menuCode}).then((res) => {
        if (res.code === 200) {
          state.authority = res.data.data
        } 
      })
      dataListPage({code: state.selectMenuData.menuCode, num: 1, size: 20, type: 0, state: 0}).then((res) => {
        if (res.code === 200) {
          state.columnPower = res.data.data
        } 
      })
    }
    window.addEventListener('beforeunload',()=>{
      localStorage.setItem("selectMenuData", JSON.stringify(state.selectMenuData))
      localStorage.setItem("menuIdArr", state.menuIdArr)
    })
    const expandedArr = computed(() => {
      if (state.menuIdArr.length > 0) {
        return state.menuIdArr
      }
    })
    const checkedArr = computed(() => {
      if (state.menuIdArr.length > 0) {
        return state.menuIdArr.filter((val, index) => {
          if (index == state.menuIdArr.length-1) {
            return val
          }
        });
      }
    })
    onMounted(() => {
      getDataList()
    })
    const getDataList = () => {
      const data = {
        menuItems: state.menuItems
      }
      if (state.menuItems == 1) {
        data.systemCode = 0
      } else {
        data.systemCode = 1
      }
      menuTree(data).then((res) => {
        if (res.code === 200) {
          let menuData = res.data
          state.menuData = menuData
        } 
      })
    }
    const tabActive = (data) => {
      state.menuItems = data
    }
    const addMenu = () => {
      state.typeId = 1
      state.menuIdArr = []
      state.isPopups = true
    }
    const addChildMenu = (data, node) => {
      state.typeId = 1
      state.isPopups = true
      state.menuIdArr = []
      state.selectMenuData = node
      parentNodesChange(data)
      state.menuIdArr = state.menuIdArr.filter(Boolean)
      state.menuIdArr.push(state.selectMenuData.menuCode)
    }
    const addAuthority = () => {
      state.typeId = 2;
      state.isPopups = true;
    }
    const addColumn = () => {
      state.typeId = 3;
      state.isPopups = true;
    }
    const addGradeSearch = () => {
      state.typeId = 4;
      state.isPopups = true;
    }
    const closeMenuPop = (val) => {
      state.isPopups = val
    }
    const menuClick = (data, node) => {
      state.menuIdArr = []
      state.selectMenuData = data
      parentNodesChange(node)
      state.menuIdArr = state.menuIdArr.filter(Boolean)
      state.menuIdArr.push(state.selectMenuData.menuCode)
      menuGet({code: data.menuCode}).then((res) => {
        if (res.code === 200) {
          state.menuInfo = res.data
        } 
      })
      buttonPage({code: data.menuCode}).then((res) => {
        if (res.code === 200) {
          state.authority = res.data.data
        } 
      })
      dataListPage({code: data.menuCode, num: 1, size: 20, type: 0, state: 0}).then((res) => {
        if (res.code === 200) {
          state.columnPower = res.data.data
        } 
      })
    }
    const parentNodesChange = (node) => {
      if(node.parent){
        for(let key in node){
          if(key == "parent"){
            state.menuIdArr.push(node[key]['data']['menuCode'])
            parentNodesChange(node[key]);
          }
        }
      }
    }
    const switchEvent = (code, val) => {
      let data = {
        buttonCode: code,
        status: val
      }
      buttonUpdateState(data).then((res) => {
        if (res.code === 200) {
          ElMessage.success({
            message: res.message,
            type: 'success'
          });
        } 
      })
    }
    const listVisibleChange = (id, val, type) => {
      let data = {
        dataListAttrCode: id
      }
      if (type == 1) {
        data.listVisible = val
      } else if (type == 2) {
        data.listHide = val
      } else if (type == 3) {
        data.listSort = val
      } else if (type == 4) {
        data.listAuth = val
      }
      updateDataListAttr(data).then((res) => {
        if (res.code === 200) {
          ElMessage.success({
            message: res.message,
            type: 'success'
          });
        } 
      })
    }
    const allowDrop = (draggingNode, dropNode, type) => {
      if (draggingNode.level === dropNode.level) {
        if (draggingNode.parent.id === dropNode.parent.id) {
          return type === "prev" || type === "next";
        }
      } else {
        return false;
      }
    }
    const sort = (draggingNode, dropNode, type, event) => {
      let arr = dropNode.parent.childNodes
      let newArr = arr.map((item) => {
        return item.data
      })
      menuSort({menuDTOList: newArr}).then((res) => {
        if (res.code === 200) {
          console.log("6666")
        } 
      })
    }
    const setQuickSearch = () => {
      state.typeId = 5
      state.isPopups = true
    }
    const setSeniorSearch = () => {
      state.typeId = 6
      state.isPopups = true
    }
    const changeAlias = () => {
      console.log("6666")
    }
    return {
      ...toRefs(state),
      tabActive,
      addMenu,
      addChildMenu,
      addAuthority,
      addColumn,
      addGradeSearch,
      closeMenuPop,
      menuClick,
      switchEvent,
      listVisibleChange,
      expandedArr,
      checkedArr,
      allowDrop,
      sort,
      setQuickSearch,
      setSeniorSearch,
      changeAlias
    };
  },
  methods: {
    delMenu() {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        menuDelete({code: this.selectMenuData.menuCode}).then((res) => {
          if (res.code === 200) {
            this.selectMenuData = {}
            this.menuIdArr = []
            ElMessage.success({ type: 'success', message: '删除成功!' });
            window.location.reload()
          } 
        })
      }).catch((err) => {
        ElMessage.error(err.message);
      });
    },
    delAuthority(code) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        buttonDelete({code: code}).then((res) => {
          if (res.code === 200) {
            this.selectMenuData = {}
            this.menuIdArr = []
            ElMessage.success({ type: 'success', message: '删除成功!' });
            window.location.reload()
          } 
        })
      }).catch((err) => {
        ElMessage.error(err.message);
      });
    },
    delColumn(code) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        dataListDelete({code: code}).then((res) => {
          if (res.code === 200) {
            ElMessage.success({ type: 'success', message: '删除成功!' });
            window.location.reload()
          } 
        })
      }).catch((err) => {
        ElMessage.error(err.message);
      });
    }
  }
};
</script>

<style lang="less" scoped>
.m-box {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.m-system {
  flex: 1;
  display: flex;
  width: 100%;
  margin-top: 22px;
  box-sizing: border-box;
  .m-system-left {
    width: 277px;
    height: 100%;
    border: 1px solid #e2e2e2;
    border-radius: 20px;
    .f-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 90%;
      height: 30px;
      margin: 13px auto 0;
      span {
        font-size: 14px;
        color: #b4b4b4;
      }
      i {
        font-size: 18px;
        font-weight: bold;
        color: #31c0fd;
        cursor: pointer;
      }
    }
    .el-tree {
      margin: 0 12px;
    }
    /deep/ .el-tree-node__content {
      padding: 6px 0;
      &:hover {
        .m-tree-node .btn {
          display: block;
        }
      }
    }
    /deep/ .el-tree-node__expand-icon {
      order: 1;
      font-size: 14px;
      -webkit-transform: rotate(0deg);
      transform: rotate(0deg);
    }
    /deep/ .el-icon-caret-right:before {
      content: "";
      color: #31c0fd;
    }
    /deep/ .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
      content: "";
      color: #31c0fd;
    }
    /deep/ .el-tree-node__expand-icon.is-leaf {
      display: none;
    }
    /deep/ .m-tree-node.m-tree-active {
      color: #31c0ff;
    }
    .m-tree-node {
      display: flex;
      justify-content: space-between;
      width: 100%;
      .icon {
        margin-right: 10px;
        font-size: 16px;
      }
      .btn {
        display: none;
        i {
          margin-left: 10px;
          font-size: 16px;
          color: #31c0fd;
        }
      }
    }
  }
  .m-system-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-left: 13px;
    .m-system-right-top {
      display: flex;
      justify-content: space-between;
      .f-left {
        flex: 1;
        border: 1px solid #e2e2e2;
        border-radius: 20px;
        .f-title {
          display: flex;
          align-items: center;
          height: 56px;
          padding: 0 20px;
          span {
            font-size: 14px;
            color: #b4b4b4;
          }
          i {
            margin-left: 30px;
            font-size: 18px;
            font-weight: bold;
            color: #31c0fd;
            cursor: pointer;
          }
        }
        .f-content {
          display: flex;
          width: 96%;
          margin: 0 auto;
          .f-img {
            margin-right: 22px;
            img {
              display: block;
              width: 39px;
              height: 39px;
              border: 3px solid #cccccc;
            }
          }
          .f-text p {
            height: 30px;
            line-height: 20px;
            span {
              padding-right: 80px;
            }
          }
        }
      }
      .f-right {
        width: 30%;
        margin-left: 13px;
        border: 1px solid #e2e2e2;
        border-radius: 20px;
        .f-title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          height: 56px;
          padding: 0 20px;
          color: #b4b4b4;
          i {
            font-size: 18px;
            font-weight: bold;
            color: #31c0fd;
            cursor: pointer;
          }
        }
        .f-content {
          width: 90%;
          margin: 0 auto;
        }
      }
    }
    .m-system-right-bottom {
      flex: 1;
      display: flex;
      justify-content: space-between;
      height: 100%;
      margin-top: 12px;
      .f-left {
        width: 30%;
        margin-right: 12px;
        border: 1px solid #e2e2e2;
        border-radius: 20px;
        .f-title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          height: 56px;
          padding: 0 20px;
          color: #b4b4b4;
          i {
            font-size: 18px;
            font-weight: bold;
            color: #31c0fd;
            cursor: pointer;
          }
        }
        .f-list {
          li {
            height: 48px;
            line-height: 48px;
            p {
              float: left;
              text-align: center;
            }
            p:nth-child(1) {
              width: 26%;
            }
            p:nth-child(2) {
              width: 26%;
            }
            p:nth-child(3) {
              width: 27%;
            }
            p:nth-child(4) {
              width: 20%;
            }
            i {
              cursor: pointer;
            }
          }
          .f-list-tit {
            border-top: 1px solid #e2e2e2;
            border-bottom: 1px solid #e2e2e2;
            p:nth-child(1) {
              border-right: 1px solid #e2e2e2;
            }
            p:nth-child(2) {
              border-right: 1px solid #e2e2e2;
            }
            p:nth-child(3) {
              border-right: 1px solid #e2e2e2;
            }
          }
        }
      }
      .f-right {
        flex: 1;
        border: 1px solid #e2e2e2;
        border-radius: 20px;
        .f-title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          height: 56px;
          padding: 0 20px;
          color: #b4b4b4;
          i {
            font-size: 18px;
            font-weight: bold;
            color: #31c0fd;
            cursor: pointer;
          }
        }
        .f-list {
          padding: 0 20px;
          margin-bottom: 20px;
          .f-tops {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            .f-checkbox {
              margin: 0 20px;
            }
            .f-tops-right {
              display: flex;
              span {
                display: block;
                width: 16px;
                height: 16px;
                margin-left: 20px;
                cursor: pointer;
                &.search {
                  background: url('../../../assets/imgs/icon_search.png') no-repeat center center;
                }
                &.sensearch {
                  background: url('../../../assets/imgs/icon_csearch.png') no-repeat center center;
                }
                &.delete {
                  background: url('../../../assets/imgs/icon_delete.png') no-repeat center center;
                }
              }
            }
          }
          .f-childlist {
            li {
              display: flex;
              align-items: center;
              height: 40px;
              padding-left: 12px;
              .name {
                padding-right: 30px;
              }
              .sort {
                padding-right: 30px;
              }
              .checkbox {
                padding-left: 30px;
              }
              &:hover {
                background-color: #e3f6ff;
              }
            }
          }
        }
      }
    }
  }
  .f-notips {
    width: 100%;
    height: 40px;
    text-align: center;
    font-size: 14px;
    color: #999999;
  }
}
</style>
